package com.goresor.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.goresor.model.Loc;
import com.goresor.service.ILocationProvider;
import com.goresor.service.LocationProviderImpl;
import com.goresor.util.GoogleTokenManager;
import com.goresor.util.GoogleTransportUtil;

@Controller
@SessionAttributes( { "user" })
public class OAuth10aController {

	public static final Logger log = LoggerFactory.getLogger(OAuth10aController.class);

	@Autowired
	private GoogleTokenManager googleTokenManager;

	@Autowired
	private ILocationProvider locationProvider;

	/**
	 * Appel au service google pour demander l'accès api par l'application
	 */
	@RequestMapping("/oauthgetrequest")
	public void oAuthGetRequestToken(HttpServletResponse response) throws Exception {
		String authorizationUrl = googleTokenManager.requestOAuthToken();
		response.sendRedirect(authorizationUrl);
		return;

	}

	/**
	 * Suite à la demande d'accès oAuthGetRequestToken(), on établit la
	 * communication avec l'api
	 * 
	 * @param oauth_token
	 * @param oauth_verifier
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/oauthcallback", method = RequestMethod.GET)
	public ModelAndView oauthcallback(@RequestParam("oauth_token") String oauth_token, @RequestParam("oauth_verifier") String oauth_verifier)
			throws IOException {
		log.info("call back appele avec succes");
		log.info("oauth_token " + oauth_token);
		log.info("oauth_verifier " + oauth_verifier);

		googleTokenManager.authorizeAccess(oauth_verifier);
		locationProvider = new LocationProviderImpl();
		Loc currentPos = locationProvider.getLocationCurrent();
		log.info("current location :" + GoogleTransportUtil.JSON_FACTORY.toString(currentPos));

		// List<Loc> locs = locationProvider.getLocationsList();

		ModelMap modelMap = new ModelMap();
		modelMap.put("currentPos", currentPos);
		return new ModelAndView("test", modelMap);
	}

}
